package com.zxd.interview.desginpattern.single;

import java.io.*;

/**
 * 单例模式 - 序列化与反序列化的问题和解决办法
 * @Author zhaoxudong
 * @Date 2020/10/28 13:55
 **/
public class SingleSerialize {

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        SerializeStaticInner instance = SerializeStaticInner.getInstance();

        System.err.println(instance.hashCode());

        // 序列化
        FileOutputStream fileOutputStream = new FileOutputStream("temp");
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
        objectOutputStream.writeObject(instance);
        objectOutputStream.close();
        fileOutputStream.close();

        // 反序列化
        FileInputStream fileInputStream = new FileInputStream("temp");
        ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
        SerializeStaticInner read = (SerializeStaticInner) objectInputStream.readObject();
        objectInputStream.close();
        fileInputStream.close();
        System.err.println(read.hashCode());


    }

    static class SerializeStaticInner implements Serializable{

        private static  SerializeStaticInner serializeStaticInner = new SerializeStaticInner();

        public static SerializeStaticInner getInstance(){
            return serializeStaticInner;
        }

        /**
         * 序列化当中的一个钩子方法
         * 避免序列化和反序列化的对象为新实例破坏单例模式的规则
         */
//        protected Object readResolve(){
//            System.err.println("调用特定的序列化方法");
//            return SerializeStaticInner.serializeStaticInner;
//        }
    }

}
